﻿#include <iostream>

#include "SDL.h"
#include "SDL_image.h"
#include <string>
#include <stdexcept>
#undef main

SDL_Texture* LoadImage(SDL_Renderer *renderer,const std::string file)
{
    SDL_Surface *loadedImage = nullptr;
    SDL_Texture *texture = nullptr;

    loadedImage = IMG_Load(file.c_str());
    if(loadedImage != nullptr)
    {
        texture = SDL_CreateTextureFromSurface(renderer,loadedImage);
        SDL_FreeSurface(loadedImage);
    }
    else
    {
        std::cout << SDL_GetError() << std::endl;
    }
    return texture;
}

void ApplySurface(int x, int y, SDL_Texture *texture, SDL_Renderer *render)
{
    SDL_Rect pos;
    pos.x = x;
    pos.y = y;
    SDL_QueryTexture(texture, nullptr, nullptr, &pos.w, &pos.h);

    SDL_RenderCopy(render, texture, nullptr, &pos);
}

int main(void)
{
    const int SCREEN_WIDTH  = 640;
    const int SCREEN_HEIGHT = 480;

    SDL_Renderer *renderer = nullptr;
    SDL_Window *window = nullptr;

    SDL_Texture *background = nullptr;
    SDL_Texture *foreground = nullptr;

    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
    {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }

    window = SDL_CreateWindow("CoverPicture", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    if(window == nullptr)
    {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }

    renderer = SDL_CreateRenderer(window,-1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
    if(renderer == nullptr)
    {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }

    try{
        background = LoadImage(renderer,"E://workspace//FFMEPG//SDL//sources//background.png");
        foreground = LoadImage(renderer,"E://workspace//FFMEPG//SDL//sources//PNG3.png");
        if(background == nullptr || foreground == nullptr)
        {
            std::cout << SDL_GetError() << std::endl;
            return 1;
        }
    }catch (const std::runtime_error &e){
        std::cout << e.what() << std::endl;
        return 1;
    }

    SDL_RenderClear(renderer);                                  //清空当前渲染器
    int bW=0, bH=0;
    SDL_QueryTexture(background, nullptr, nullptr, &bW, &bH);   //获取SDL_Texture的宽和高
    ApplySurface(0, 0, background, renderer);                   //将图片按照位置插入到渲染器中
    ApplySurface(bW, 0, background, renderer);
    ApplySurface(0, bH, background, renderer);
    ApplySurface(bW, bH, background, renderer);

    int iW=0, iH=0;
    SDL_QueryTexture(foreground, nullptr, nullptr, &iW, &iH);
    int x = SCREEN_WIDTH / 2 - iW / 2;
    int y = SCREEN_HEIGHT / 2 - iH / 2;
    ApplySurface(x, y, foreground, renderer);

    SDL_RenderPresent(renderer);                               //用渲染器更新显示窗口
    SDL_Delay(8000);

    SDL_DestroyTexture(background);
    SDL_DestroyTexture(foreground);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
